package com.newhis.utils;


import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultJwsHeader;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    private static final long expireMillions = 30*60*1000L;
    private static final String secret = "A8RHIUTR346DGHT568DFGD";
    public static String getAuthToken(Object o){
        DefaultJwsHeader header = new DefaultJwsHeader();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setHeader((Map<String, Object>) header)
                .setExpiration(new Date(System.currentTimeMillis() + expireMillions))
                .setPayload(JSON.toJSONString(o))
                .setClaims(new HashMap<>())
                .signWith(SignatureAlgorithm.HS256, secret.getBytes());
        return jwtBuilder.compact();
    }

    public static boolean validToken(String token){
        if (StringUtils.isBlank(token)){
            return false;
        }
        Object body = Jwts.parser().setSigningKey(secret.getBytes()).parse(token).getBody();
        System.out.println(JSON.toJSON(body));
        return true;
    }

}
